<template>
  <div>
    <el-row v-if="Object.keys(slaves).length > 0">
      <el-col v-for="slave in Object.values(slaves)" :key="slave.uuid">
        <div class="slave" @click="slaveClick(slave.uuid)">
          <span>客户机: {{ slave.client_name }}</span>
        </div>
      </el-col>
    </el-row>
    <div v-else style="color: #c0c4cc">暂无客户端连接...</div>
    <SlaveItemWnd
      v-if="this.showItemWnd"
      v-on:wnd-close="this.itemWndClose"
      :slave_name="this.selectedSlave.client_name"
      :slave_uuid="this.selectedSlave.uuid"
    ></SlaveItemWnd>
  </div>
</template>

<script>
import SlaveItemWnd from "@/components/SlaveItemWnd";
export default {
  name: "SlaveWnd",
  components: {
    SlaveItemWnd,
  },
  data: function () {
    return {
      selectedSlave: {},
      slaves: {},
      autoRefresh: null,
      showItemWnd: false,
    };
  },
  methods: {
    enableRefresh() {
      console.log("enable auto refresh");
      this.autoRefresh = setInterval(() => {
        this.refresh();
      }, 10000);
    },
    disableRefresh() {
      if (this.autoRefresh != null) {
        console.log("disable auto refresh");
        clearInterval(this.autoRefresh);
      }
    },
    refresh() {
      this.$axios.get("slave/list").then((resp) => {
        let data = resp.data.data;
        let slaves = {};
        data.forEach((element) => {
          slaves[element.uuid] = element;
        });
        this.slaves = slaves;
        console.log("refresh: ");
        console.log(this.slaves);
      });
    },
    slaveClick(uuid) {
      console.log("slave click: " + uuid);
      this.selectedSlave = this.slaves[uuid];
      this.showItemWnd = true;
      this.disableRefresh();
    },
    itemWndClose() {
      console.log("item wnd close");
      this.showItemWnd = false;
      this.selectedSlave = {};
      this.enableRefresh();
    },
  },
  mounted: function () {
    this.enableRefresh();
    this.refresh();
  },
  beforeDestroyed: function () {
    this.disableRefresh();
  },
};
</script>

<style>
.el-col {
  border-radius: 4px;
}
.slave {
  text-align: left;
  padding: 10px;
  background-color: #409eff;
  font-size: 24px;
  font-weight: 800;
  user-select: none;
}
.slave:hover {
  cursor: pointer;
}
</style>
